package com.wolf.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.wolf.common.constant.ProductConstant;
import com.wolf.common.to.SkuHasStockTo;
import com.wolf.common.to.SkuReductionTo;
import com.wolf.common.to.SpuBoundTo;
import com.wolf.common.to.es.SkuEsModel;
import com.wolf.common.utils.R;
import com.wolf.gulimall.product.entity.*;
import com.wolf.gulimall.product.feign.CouponFeignService;
import com.wolf.gulimall.product.feign.SearchFeignService;
import com.wolf.gulimall.product.feign.WareFeignService;
import com.wolf.gulimall.product.service.*;
import com.wolf.gulimall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wolf.common.utils.PageUtils;
import com.wolf.common.utils.Query;

import com.wolf.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 保存spu 信息
     * TODO 待完善
     *
     * @param spuSaveVo spu 信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuSaveVo(SpuSaveVo spuSaveVo) {

        //1.保存spu基本信息   pms_sku_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        //2.保存spu 描述图片 pms_spu_info_desc
        List<String> decriptions = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        // join 以逗号将 decriptions 集合数据隔离开,返回一个字符串
        spuInfoDescEntity.setDecript(String.join(",", decriptions));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        //3.保存spu 的图片集 pms_spu_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        //4.保存spu 的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(baseAttr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(baseAttr.getAttrId());
            AttrEntity attrEntity = attrService.getById(baseAttr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
            productAttrValueEntity.setQuickShow(baseAttr.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProduceAttr(productAttrValueEntities);

        //5.保存spu 的积分信息  gulimail_sms -> sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu 的积分信息失败!!!");
        }

        //6.保存spu 对应的所有的sku信息
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(sku -> {

                //6.1) 保存sku的基本信息 pms_sku_info
                String defaultImage = "";
                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImage = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                //6.2) 保存sku的图片信息 pms_sku_images
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> !StringUtils.isEmpty(entity)).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);

                //6.3) 保存sku的销售属性信息 pms_sku_sale_attr_value
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = sku.getAttr().stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //6.2) 保存sku的 优惠满减信息 gulimail_sms -> sms_sku_ladder -> sms_sku_full_reduction -> sms_member_price -> sms_spu_bounds
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) > 0) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku的 优惠满减信息失败!!!");
                    }
                }
            });
        }
    }


    /**
     * 保存spu基本信息   pms_sku_info
     *
     * @param spuInfoEntity spu基本信息
     */
    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    /**
     * spu检索
     *
     * @param params 参数
     * @return spu数据
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("id", key).or().like("spu_name", key);
            });
        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("publish_status", status);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

    /**
     * 商品上架
     *
     * @param spuId spuId
     */
    @Override
    public void spuUp(Long spuId) {
        //1.查出当前spuId对应的所有sku信息,品牌名称
        List<SkuInfoEntity> skuInfos = skuInfoService.getSkuInfoBySpuId(spuId);
        List<Long> skuIds = skuInfos.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //查询当前sku 的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.baseAttrListforspu(spuId);
        //spu 商品属性ID集合
        List<Long> attrIds = productAttrValueEntities.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        //根据属性ID集合查询出可被检索的ID集合
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        Set<Long> set = new HashSet<>(searchAttrIds);
        //获取商品规格属性信息集合
        List<SkuEsModel.Attrs> attrsList = productAttrValueEntities.stream().filter(productAttrValueEntity -> set.contains(productAttrValueEntity.getAttrId()))
                .map(productAttrValueEntity -> {
                    SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(productAttrValueEntity, attrs);
                    return attrs;
                })
                .collect(Collectors.toList());
        //2.分装每个sku信息
        List<SkuEsModel> skuEsModels = skuInfos.stream().map(skuInfoEntity -> {
            //组装需要的数据
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            //1.发送远程调用,查询是否有库存
            Map<Long, Boolean> stockMap = null;
            try {
                R skuHasStock = wareFeignService.getSkuHasStock(skuIds);
                if (skuHasStock.getCode() == 0) {
                    log.info("库存服务调用成功");
                }
                List<SkuHasStockTo> skuHasStockTos = (List<SkuHasStockTo>) skuHasStock.get("data");
                // R 类型返回的数据skuHasStockTos 的类型是 LinkedHashMap 并不是List<SkuHasStockTo>
                //这里还需要进行转换
                String s = JSON.toJSONString(skuHasStockTos);
                List<SkuHasStockTo> skuHasStockToList = JSON.parseArray(s, SkuHasStockTo.class);
                stockMap = skuHasStockToList.stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, itrem -> itrem.getHasStock()));
            } catch (Exception e) {
                log.error("库存服务调用异常:", e);
            }
            //2. 评分热度
            skuEsModel.setHotScore(0L);
            //3.查询品牌 / 分类名称
            BrandEntity brandEntity = brandService.getById(skuInfoEntity.getBrandId());
            CategoryEntity categoryEntity = categoryService.getById(skuInfoEntity.getCatalogId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setCatalogName(categoryEntity.getName());
            skuEsModel.setAttrs(attrsList);
            if (stockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(stockMap.get(skuInfoEntity.getSkuId()));
            }
            return skuEsModel;
        }).collect(Collectors.toList());
        //TODO 将数据发送给search服务进行保存
        R r = searchFeignService.productStatusUp(skuEsModels);
        if (r.getCode() == 0) {
             log.info("检索服务远程调用成功!!");
             baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
             log.info("修改商品状态完成!!!");
        }//TODO 重读调用接口,幂等性 ,重试机制


    }

    /**
     * 根据商品的skuId 获取 spu信息
     * @param skuId 商品的skuId
     * @return spu信息
     */
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        Long spuId = skuInfoEntity.getSpuId();
        return getById(spuId);
    }


}